package com.lazydong.apiforward.clientupdate.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.lazydong.apiforward.clientupdate.constant.UpdateConstant;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class OpenExeUtil {

    public static void openClientExe() {
        String batDir = UpdateConstant.CLIENT_UPDATE_DIR + File.separator + "bat";
        // 先写启动更新程序的脚本

        String startUpdateContent = JarResFileCopyUtil.loadResourceFile(null, "startClient.bat");
        Map<String, String> param1 = new HashMap<>();
        param1.put("panFu", UpdateConstant.CLIENT_EXE_PATH.substring(0, 2));
        param1.put("clientUpOneLevelPath", FileUtil.getParent(UpdateConstant.CLIENT_EXE_PATH, 1));
        param1.put("clientPath", UpdateConstant.CLIENT_EXE_PATH);
        startUpdateContent = StrUtil.format(startUpdateContent, param1);

        String startUpdatePath = batDir + File.separator + "startClient.bat";
        FileUtil.writeString(startUpdateContent, startUpdatePath, StandardCharsets.UTF_8);

        // 写任务计划脚本
        String launchProcessContent = JarResFileCopyUtil.loadResourceFile(null, "launchProcess.bat");
        Map<String, String> param2 = new HashMap<>();
        param2.put("taskName", "startClientApiForward");
        param2.put("batPath", startUpdatePath);
        launchProcessContent = StrUtil.format(launchProcessContent, param2);
        String launchProcessPath = batDir + File.separator + "launchProcess.bat";
        FileUtil.writeString(launchProcessContent, launchProcessPath, StandardCharsets.UTF_8);
        try {
            ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", launchProcessPath);
            pb.directory(new File(UpdateConstant.CLIENT_DIR));
            pb.start();
        } catch (IOException e) {
            System.err.println("启动失败: " + e.getMessage());
        }
    }
}
